package com.qf.user.factory.loginfactory;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.User;
import com.qf.common.core.exception.CustomerException;
import com.qf.common.core.utils.JwtUtils;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.user.mapper.UserMapper;
import com.qf.user.param.LoginParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zdl
 * @date 2025/3/22
 */
@Service
public class PhoneAndVerificationCodeLoginRation implements LoginRation{
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public String login(LoginParam loginParam) { //必传相关参数: phone, code, loginType=2
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, loginParam.getPhone()));
        if(user == null){
            throw new CustomerException("3003","手机号不存在");
        }
        String cachCode  = redisUtil.getCacheObject(loginParam.getPhone());
        if(cachCode == null || !cachCode.equals(loginParam.getCode())){
            throw new CustomerException("3004","验证码错误");
        }
        //返回token  使用jwt作为token的生成方式
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        return JwtUtils.createJwt(map);
    }
}
